package com.qf.service.Impl;

import com.qf.dto.Md5;
import com.qf.dto.ResultCode;
import com.qf.dto.UserDto;
import com.qf.exceptions.AddDataException;
import com.qf.mapper.UsersMapper;
import com.qf.pojo.Users;
import com.qf.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import sun.security.util.Password;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.UUID;

@Service
@Transactional
public class UsersServiceImpl  implements UsersService {

    private UsersMapper usersMapper;
    @Autowired
    public void setUsersMapper(UsersMapper usersMapper) {
        this.usersMapper = usersMapper;
    }



    @Override
    public void insertUsers(UserDto users) {
        if (users.getUsername()==null) {
            //数据不符合我们的要求,返回结果,中断操作,抛出异常
            throw new AddDataException("用户名为空", ResultCode.NULL_USERNAME);
        }
        if(users.getPassword()==null||users.getPassword().length()>10){
            throw new AddDataException("密码为空或者不符合规范", ResultCode.NULL_PASSWORD);
        }
        if(users.getRepeatPassword()==null||!users.getPassword().equals(users.getRepeatPassword())){
            throw new AddDataException("两次密码不一致", ResultCode.NULL_DATA);
        }
         //判断用户名是否存在
        Users usersByName = usersMapper.findUsersByName(users.getUsername());
        if(usersByName!=null){
            throw new AddDataException("用户名已存在", ResultCode.NULL_DATA);
         }

        //jiami
        String salt = Md5.RandomSalt();
        String newpassword = Md5.md5AndSalt(salt, users.getPassword());
        System.err.println(newpassword);


        Users newUserS=new Users();
        newUserS.setPassword(newpassword);
        newUserS.setUsername(users.getUsername());
        newUserS.setPasswordsalt(salt);


        usersMapper.insertUsers(newUserS);



    }

    @Override
    public void login(Users users) {
        if(users.getUsername()==null||users.getPassword()==null){
            throw new AddDataException("用户名或者密码为空", ResultCode.NULL_DATA );
        }
        Users sqlUsers = usersMapper.findUsersByName(users.getUsername());
        if(sqlUsers==null){
            throw new AddDataException("用户名不存在", ResultCode.USER_NOT_EXIST);
        }
        String passwordsalt = sqlUsers.getPasswordsalt();

        String jmPassword = Md5.md5AndSalt(passwordsalt, users.getPassword());
        System.err.println(sqlUsers.getPassword()+"正确的......");
        System.err.println(jmPassword);
        if(!jmPassword.equals(sqlUsers.getPassword())){
            throw new AddDataException("用户名或者密码不正确", ResultCode.USER_NOT_EXIST);
        }




    }

}
